package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmNewsMaterialMapper  wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService autoScanService;

    @Autowired
    private WmNewsTaskService taskService;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //分页查询
        IPage page = new Page(dto.getPage() ,dto.getSize());

        //条件查询
            //状态精确查询
        LambdaQueryWrapper<WmNews> wmNewsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        wmNewsLambdaQueryWrapper.eq(dto.getStatus() != null ,
                WmNews::getStatus ,
                dto.getStatus());
            //频道精确查询
        wmNewsLambdaQueryWrapper.eq(dto.getChannelId() != null ,
                WmNews::getChannelId,
                dto.getChannelId());
            //时间范围范围查询
        wmNewsLambdaQueryWrapper.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null ,
                WmNews::getPublishTime,
                dto.getBeginPubDate(), dto.getEndPubDate());
            //关键字模糊查询
        wmNewsLambdaQueryWrapper.like(dto.getKeyword() != null ,
                WmNews::getTitle,
                dto.getKeyword());

        //该用户文章
        wmNewsLambdaQueryWrapper.eq(WmThreadLocalUtil.getUser().getId() != null ,
                WmNews::getUserId ,WmThreadLocalUtil.getUser().getId());

        //排序
        wmNewsLambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page(page,wmNewsLambdaQueryWrapper);
        //返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    @GlobalTransactional
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        if (null == dto || StringUtils.isEmpty(dto.getContent())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //更新或保存文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //补充其他数据
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short)1);
        wmNews.setSubmitedTime(new Date());

        //对封面自动进行处理
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String join = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(join);
        }
        saveOrUpdateWmNews(wmNews);

        //保存草稿
        if(dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //从内容中提取图片
        List<String> urls = ectractUrlInfo(dto.getContent());

        //保存内容中的图片和素材之间的关系
        saveRelativeInfoForContent(wmNews,urls,(short)0);

        //保存文章封面图片与素材的关系
        saveRelativeInfoForCover(wmNews,dto,(short)1,urls);

        //进入审核环节
        //autoScanService.autoScanWmNews(wmNews.getId());
        taskService.addWmNewsToTask(wmNews);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;
    /**
     * 文章上架或下架
     *
     * @param dto
     * @return
     */

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //判断id是否为空
        if (null == dto.getId()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "文章Id不可缺少");
        }
        //判断文章是否存在
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()));
        wmNews.setEnable(dto.getEnable());
        BeanUtils.copyProperties(wmNews , dto);
        System.out.println(dto.getEnable());
        if (null == wmNews) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST , "文章不存在");
        }
        //判断文章状态status == 8 待发布
        if (wmNews.getStatus() != 8 && wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "当前文章不是发布状态,不能上下架");
        }
        wmNewsMapper.updateById(wmNews);


        return null;
    }

    /**
     * 保存文章封面图片与素材的关系
     * @param wmNews
     * @param dto
     * @param type
     * @param  urls
     */
    private void saveRelativeInfoForCover(WmNews wmNews, WmNewsDto dto, short type,List<String> urls) {

        List<String> images = dto.getImages();
        if (dto.getType() == -1) {
            if (urls.size() >= 3) {
                images = urls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else if (urls.size() >=1) {
                images = urls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
        }
        //更新WmNews数据
        updateById(wmNews);
        saveRelativeInfoForContent(wmNews,images,type);
    }



    /**
     * 保存内容中的图片和素材之间的关系
     * @param wmNews
     * @param urls
     * @param type
     */
    private void saveRelativeInfoForContent(WmNews wmNews, List<String> urls, short type) {

        saveRelativeInfo(wmNews, urls, type);
    }

    private void saveRelativeInfo(WmNews wmNews, List<String> urls, short type) {
        //去除重复图片地址
        if (urls.size() > 0) {
            urls = urls.stream().distinct().collect(Collectors.toList());
            //根据url查询素材对象
            WmUser wmUser = WmThreadLocalUtil.getUser();
            if (null == wmUser) {
                throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
            }

            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().
                    in(WmMaterial::getUrl, urls).
                    eq(WmMaterial::getUserId, wmUser.getId()));
            //判断素材中旁边是否被删除
            if (null == wmMaterials || urls.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            //保存数据和素材之间的关系
            List<Integer> ids = wmMaterials.stream().map(item -> item.getId()).collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelations(ids, wmNews.getId(), type);
        }
    }

    /**
     * 从内容中提取图片数据
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> result = new ArrayList<>();
        for (Map map : list) {
            if ("image".equals(map.get("type"))) {
                result.add(map.get("value").toString());
            }
        }
        return result;
    }

    /**
     * 保存或更新数据
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if (null != wmNews.getId()) {
            //更新
            //删除关联数据
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }else {
            //新增
            save(wmNews);
        }
    }
}